package cc.bookcloud.tool.ocr.util;

import com.lowagie.text.Font;
import com.lowagie.text.*;
import com.lowagie.text.rtf.RtfWriter2;
import cc.bookcloud.tool.ocr.config.ExportConstants;
import cc.bookcloud.tool.ocr.domain.TableFileds;
import cc.bookcloud.tool.ocr.domain.Tables;
import cc.bookcloud.tool.ocr.mapper.TableMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p> 创建word文档 </p>
 *
 * @author : zhaoqiuyue
 * @description : 步骤:
 *                  1、建立文档
 *                  2、创建一个书写器
 *                  3、打开文档
 *                  4、向文档中写入数据
 *                  5、关闭文档
 * @date : 2019/11/8 15:45
 */
@Service
public class TableToWordUtil {

    @Resource
    private TableMapper tableMapper;

    /**
     * 生成word文档
     *
     * @param tables：该数据库下所有表信息
     * @param dbName :数据库名
     * @param fileName：生成文件地址
     * @param title:文件内容标题
     * @return: void
     */
    public void toWord(List<Tables> tables, String dbName, String fileName, String title) {
        Document document = new Document(PageSize.A4);
        try {
            // 创建文件夹
            File dir = new File(ExportConstants.FILE_PATH);
            dir.mkdirs();

            // 创建文件
            File file = new File(fileName);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
            file.createNewFile();

            // 写入文件信息
            RtfWriter2.getInstance(document, new FileOutputStream(fileName));
            document.open();
            Paragraph ph = new Paragraph();
            Font f = new Font();
            Paragraph p = new Paragraph(title, new Font(Font.NORMAL, 24, Font.BOLDITALIC, new Color(0, 0, 0)));
            p.setAlignment(1);
            document.add(p);
            ph.setFont(f);
            for (int i = 0; i < tables.size(); i++) {
                String table_name = tables.get(i).getTableName();
                String table_comment = tables.get(i).getComments();
                List<TableFileds> fileds = tableMapper.getTableInfo(tables.get(i).getTableName(),dbName);
                List<String> columnNames = fileds.stream().map(TableFileds::getColumnName).collect(Collectors.toList());
                //List<TableFileds> tableFileds = filterList(fileds);
                //System.out.println(tableFileds);

                Set<String> set = new HashSet<>();
                List<TableFileds> tableFileds = new ArrayList<>();
                ArrayList<TableFileds> idList = new ArrayList<>();
                for (TableFileds filed :fileds) {
                    if(columnNames.contains("BIZID")){
                        if("BIZID".equals(filed.getColumnName())){
                            idList.add(filed);
                        }else {
                            if(set.add(filed.getColumnName())){
                                tableFileds.add(filed);
                            }
                        }
                    }else if(columnNames.contains("ELE_ID")){
                        if("ELE_ID".equals(filed.getColumnName())){
                            idList.add(filed);
                        }else {
                            if(set.add(filed.getColumnName())){
                                tableFileds.add(filed);
                            }
                        }
                    }else if(columnNames.contains("BIZ_ID")){
                        if("BIZ_ID".equals(filed.getColumnName())){
                            idList.add(filed);
                        }else {
                            if(set.add(filed.getColumnName())){
                                tableFileds.add(filed);
                            }
                        }
                    }else {
                        if(set.add(filed.getColumnName())){
                            tableFileds.add(filed);
                        }
                    }
                }
                //处理主键id不为没有主键约束时，数据重复得问题
                if(idList.size()>0){
                    if(idList.size()==1){
                        tableFileds.addAll(idList);
                    }else {
                        List<String> collect = idList.stream().map(TableFileds::getConstraintType).collect(Collectors.toList());
                        if(collect.contains("P")){
                            for (TableFileds filed : idList) {
                                if("P".equals(filed.getConstraintType())){
                                    if(set.add(filed.getColumnName())){
                                        tableFileds.add(filed);
                                    }
                                }
                            }
                        }else {
                            tableFileds.add(idList.get(0));
                        }
                    }
                }
                //将bizid放到list的第一位
                 if(columnNames.contains("BIZID")){
                    List<TableFileds> collect = tableFileds.stream().filter(a ->a.getColumnName().equals("BIZID")).collect(Collectors.toList());
                    tableFileds.removeIf(b->b.getColumnName().equals("BIZID"));
                    tableFileds.add(0,collect.get(0));
                }else if(columnNames.contains("ELE_ID")){
                    List<TableFileds> collect = tableFileds.stream().filter(a ->a.getColumnName().equals("ELE_ID")).collect(Collectors.toList());
                    tableFileds.removeIf(b->b.getColumnName().equals("ELE_ID"));
                    tableFileds.add(0,collect.get(0));
                }else if(columnNames.contains("BIZ_ID")){
                     List<TableFileds> collect = tableFileds.stream().filter(a ->a.getColumnName().equals("BIZ_ID")).collect(Collectors.toList());
                     tableFileds.removeIf(b->b.getColumnName().equals("BIZ_ID"));
                     tableFileds.add(0,collect.get(0));
                 }


                String all = "" + (i+1) + " 、表名称:" + table_name + "（" + table_comment + "）";
                Table table = new Table(5);

                document.add(new Paragraph(""));

                table.setBorderWidth(1);
                table.setPadding(0);
                table.setSpacing(0);

                //添加表头的元素，并设置表头背景的颜色
                Color chade = new Color(176, 196, 222);

                Cell cell = new Cell("代码");
                addCell(table, cell, chade);
                cell = new Cell("名称");
                addCell(table, cell, chade);
                cell = new Cell("字段类型");
                addCell(table, cell, chade);
                cell = new Cell("是否主键");
                addCell(table, cell, chade);
                cell = new Cell("备注");
                addCell(table, cell, chade);

                table.endHeaders();

                // 表格的主体
                for (int k = 0; k < tableFileds.size(); k++) {
                    addContent(table, cell, tableFileds.get(k).getColumnName());
                    addContent(table, cell, tableFileds.get(k).getComments());
                    addContent(table, cell, tableFileds.get(k).getDataType());
                    if(tableFileds.get(k).getConstraintType()!=null){
                        addContent(table, cell, tableFileds.get(k).getConstraintType().equals("P") ? "是" : "否");
                    }else {
                        addContent(table, cell,"否");
                    }
                    addContent(table, cell, "");
                }
                Paragraph pheae = new Paragraph(all);
                //写入表说明
                document.add(pheae);
                //生成表格
                document.add(table);
            }
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<TableFileds> filterList(List<TableFileds> fileds) {
        Set<String> noSame = fileds.stream().map(TableFileds::getColumnName).collect(Collectors.toSet());
        List<TableFileds> finalList = new ArrayList<>();
        if(noSame.size()!=fileds.size()){
            for (String s : noSame) {
                List<TableFileds> filterFields = fileds.stream().filter(field -> field.getColumnName().equals(s)).collect(Collectors.toList());
                if(filterFields.size()>1){
                    filterFields = filterFields.stream().filter(fz -> fz.getComments() != null).collect(Collectors.toList());
                    if(s.equals("BIZID")){
                        filterFields.stream().filter(fz-> fz.getConstraintType().equals("P"))
                                .findFirst()
                                .ifPresent(fz->finalList.add(fz));
                    }else {
                        filterFields.stream().findFirst()
                                .ifPresent(fz->finalList.add(fz));
                    }

                }else {
                    finalList.add(filterFields.get(0));
                }
            }
        }else {
            finalList.addAll(fileds);
        }
        return finalList;
    }

    /**
     * 添加表头到表格
     *
     * @param table
     * @param cell
     * @param chade
     */
    private void addCell(Table table, Cell cell, Color chade) {
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(chade);
        table.addCell(cell);
    }

    /**
     * 添加内容到表格
     *
     * @param table
     * @param content
     */
    private void addContent(Table table, Cell cell, String content) {
        cell = new Cell(content);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
    }

}
